<?php

namespace User\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\View\Model\ViewModel;
use Zend\Form\Form;
use User\Options\UserControllerOptionsInterface;
use User\Service\User as UserService;

class UserController extends AbstractActionController
{
    const ROUTE_CHANGEPASSWD = 'user/changepassword';
    const ROUTE_LOGIN        = 'user/login';
    const ROUTE_REGISTER     = 'user/register';
    const ROUTE_CHANGEEMAIL  = 'user/changeemail';

    const CONTROLLER_NAME    = 'user';

    /**
     * @var UserService
     */
    protected $userService;


    protected $registerForm;
    protected $loginForm;
    protected $options;

    public function indexAction()
    {
        return new ViewModel();
    }

    public function loginAction()
    {
        $request = $this->getRequest();
        $form = $this->getLoginForm();

        if ($this->getOptions()->getUseRedirectParameterIfPresent()) {
            $redirect = $request->getQuery()->get('redirect', (!empty($post['redirect'])) ? $post['redirect'] : false);
        } else {
            $redirect = false;
        }

        $redirectUrl = $this->url()->fromRoute(static::ROUTE_LOGIN)
            . ($redirect ? '?redirect=' . rawurlencode($redirect) : '');

        $prg = $this->prg($redirectUrl, true);

        if ($prg instanceof Response) {
            return $prg;
        } elseif ($prg === false) {
            return array(
                'form' => $form,
                'enableRegistration' => $this->getOptions()->getEnableRegistration(),
                'redirect' => $redirect,
            );
        }

        $post = $prg;

        if (!$request->isPost()) {
            return array(
                'form' => $form,
                'redirect'  => $redirect,
                'enableRegistration' => $this->getOptions()->getEnableRegistration(),
            );
        }

        $form->setData($post);

        if (!$form->isValid()) {
            return array(
                'form' => $form,
                'redirect'  => $redirect,
                'enableRegistration' => $this->getOptions()->getEnableRegistration(),
            );
            //$this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
            //return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN).($redirect ? '?redirect='. rawurlencode($redirect) : ''));
        }
        return array(
            'form' => $form,
            'redirect'  => $redirect,
            'enableRegistration' => $this->getOptions()->getEnableRegistration(),
        );
        // clear adapters
        //$this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
        //$this->zfcUserAuthentication()->getAuthService()->clearIdentity();

        //return $this->forward()->dispatch(static::CONTROLLER_NAME, array('action' => 'authenticate'));
    }


    /*
     * Register new user
     */
    public function registerAction()
    {
        $form = $this->getRegisterForm();

        $request = $this->getRequest();
        $userService = $this->getUserService();

        if ($this->getOptions()->getUseRedirectParameterIfPresent() && $request->getQuery()->get('redirect')) {
            $redirect = $request->getQuery()->get('redirect');
        } else {
            $redirect = false;
        }

        $redirectUrl = $this->url()->fromRoute(static::ROUTE_REGISTER)
            . ($redirect ? '?redirect=' . rawurlencode($redirect) : '');

        $prg = $this->prg($redirectUrl, true);

        if ($prg instanceof Response)
        {
            return $prg;
        } elseif ($prg === false)
        {
            return array(
                'form' => $form,
                'enableRegistration' => $this->getOptions()->getEnableRegistration(),
                'redirect' => $redirect,
            );
        }

        $post = $prg;
        $user = $userService->register($post);

        $redirect = isset($prg['redirect']) ? $prg['redirect'] : null;

        if (!$user) {
            return array(
                'form' => $form,
                'enableRegistration' => $this->getOptions()->getEnableRegistration(),
                'redirect' => $redirect,
            );
        }

        return $this->redirect()->toRoute('user' , array('controller' => 'user' , 'action' => 'register-success'));

        if($userService->getOptions->getLoginAfterRegistration)
        {
            $entityFields = $userService->getOptions()->uthIdentityFields();
            if(in_array('email' , $entityFields))
            {

            }
            elseif(in_array('username' , $entityFields))
            {

            }
        }

    }

    public function registerSuccessAction()
    {
        return new ViewModel();
    }


    public function getUserService()
    {
        if(!$this->userService)
        {
            $this->setUserService($this->getServiceLocator()->get('user_service'));
        }
        return $this->userService;
    }

    public function setUserService(UserService $userService)
    {
        $this->userService = $userService;
        return $this;
    }

    /*
     * Get register form
     */

    public function getRegisterForm()
    {
        if(!$this->registerForm)
        {
            $this->setRegisterForm($this->getServiceLocator()->get('user_register_form'));
        }
        return $this->registerForm;
    }

    public function setRegisterForm(Form $registerForm)
    {
        $this->registerForm = $registerForm;
        //return $this;
    }


    /*
     * get login form
     *
     */
    public function getLoginForm()
    {
        if(!$this->loginForm)
        {
            $this->setLoginForm($this->getServiceLocator()->get('user_login_form'));
        }
        return $this->loginForm;
    }

    /*
     * set login form
     */
    public function setLoginForm(Form $loginForm)
    {
        $this->loginForm = $loginForm;
        return $this;
    }

    /*
     * get Options
     * @return UserConrtollerOptionInterface
     */
    public function getOptions()
    {
        if(!$this->options instanceof UserControllerOptionsInterface)
        {
            $this->setOptions($this->getServiceLocator()->get('user_module_options'));
        }
        return $this->options;
    }

    /**
     * set Options
     *
     * @param UserControllerOptionsInterface $options
     * @return UserController
     */
    public function setOptions(UserControllerOptionsInterface $options)
    {
        $this->options = $options;
        return $this;
    }

}

